﻿using System;
using System.Collections.Generic;
using System.Text;
using formworks.DBO;
using formworks.DBO.Core;
using System.Data;
using System.Web;

namespace formworks
{
    public class UnityToolkit
    {
        private static string EmptyXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><null></null>";

        public static DBSessionFactory factory;
        private static DBSession session;

        /// <summary>
        /// 验证返回数据
        /// </summary>
        /// <param name="response">返回字符串</param>
        /// <param name="context">HttpContext对象</param>
        public static void validateResponse(string response, HttpContext context)
        {
            context.Response.Charset = "UTF-8";

            if (null == response
                || response.Trim().Equals(""))
                context.Response.Redirect("Login.aspx");
            else
                context.Response.Write(response);
            //
            context.Response.Flush();
        }

        public static void normalResponse(string response, HttpContext context)
        {

            context.Response.Charset = "UTF-8";
            if (null == response
                || response.Trim().Equals(""))
                context.Response.Write(EmptyXML);
            else
                context.Response.Write(response);
            //
            context.Response.Flush();
        }


        /// <summary>
        /// 验证返回数据
        /// </summary>
        /// <param name="response">返回字符串</param>
        /// <param name="context">HttpContext对象</param>
        public static void validateResponse(string response, HttpContext context, string outputFileName)
        {
            context.Response.Clear();
            context.Response.BufferOutput = true;
            //设定输出的字符集
            context.Response.Charset = "UTF-8";

            //导出excel选项不为空情况下 设置返回头为excel头
            string report = UnityToolkit.resetNull2Empty(context.Request.Params["report"]);

            //默认为打印或者其他的输出
            switch (report)
            {
                case "excel":
                    {
                        context.Response.AppendHeader("Content-Disposition",
                            string.Format("attachment;filename={0}_{1}.xls",
                                HttpUtility.UrlEncode(outputFileName),
                                DateTime.Now.ToShortDateString())
                         );
                        //设置导出文件的格式
                        context.Response.ContentType = "application/ms-excel";
                    }
                    break;
            }

            //if (!report.Equals("")
            //    && !report.Equals("print"))
            //{



            //    //context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //}

            //判断返回值是否为空字符串，若为空，则说明未登录。否则返回请求内容
            if (null == response
                || response.Trim().Equals(""))
                context.Response.Redirect("Login.aspx");
            else
                context.Response.Write(response);
            //把HTML写回浏览器
            context.Response.Flush();
        }


        /// <summary>
        /// 表格构建
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string constructionTableGridJson(DataTable dt)
        {
            return "{ \"total\":" + dt.Namespace + ",\"rows\":"
                   + (0 == dt.Rows.Count ? "[]" : dataTableToJson(dt))
                   + "}";
        }


        /// <summary>
        /// 获取排序的DataTable
        /// </summary>
        /// <param name="page">当前页数</param>
        /// <param name="rows">每页数量</param>
        /// <param name="sqlStr">查询条件</param>
        /// <param name="db">指定数据库对象</param>
        /// <returns></returns>
        public static DataTable paginationDataTable(int page, int rows, string sqlStr, DBSession session)
        {
            try
            {
                //DB db = new DB();
                DataTable dt = null;
                if (0 != page
                    || 0 != rows)
                {
                    int rowCount = session.paginationRowCount(sqlStr);

                    string sqls = session.pagination(sqlStr, page, rows, rowCount);
                    dt = session.createQuery(
                        sqls
                    ).Tables[0];

                    dt.Namespace = rowCount.ToString();
                }
                else
                {
                    dt = session.createQuery(sqlStr.Replace("{0}", "")).Tables[0];
                }
                //close session
                //session.closeSession();
                return dt;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 获取排序的DataTable
        /// </summary>
        /// <param name="page">当前页数</param>
        /// <param name="rows">每页数量</param>
        /// <param name="sqlStr">查询条件</param>
        /// <returns></returns>
        public static DataTable paginationDataTable(int page, int rows, string sqlStr)
        {
            try
            {

                factory = new DBConfigure().buildSessionFactory();
                session = factory.openSession();

                //DB db = new DB();
                DataTable dt = null;
                if (0 != page
                    || 0 != rows)
                {
                    int rowCount = session.paginationRowCount(sqlStr);

                    string sqls = session.pagination(sqlStr, page, rows, rowCount);
                    dt = session.createQuery(
                        sqls
                    ).Tables[0];

                    dt.Namespace = rowCount.ToString();
                }
                else
                {
                    dt = session.createQuery(sqlStr.Replace("{0}", "")).Tables[0];
                }
                //close session
                session.closeSession();
                return dt;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }


        }


        /// <summary>
        /// dt 2 xml
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string dataTableToXML(DataTable dt)
        {
            StringBuilder XmlString = new StringBuilder();
            string newsContent = "";
            if (dt != null && dt.Rows.Count > 0)
            {
                //JsonString.Append("{ ");
                XmlString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                XmlString.Append(string.Format("<TinyNews RowCount=\"{0}\">", dt.Namespace));


                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //
                    XmlString.Append("<item ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Columns[j].ColumnName.ToString().Equals("NewsContent"))
                        {
                            newsContent = dt.Rows[i][j].ToString().Trim();
                            continue;
                        }

                        XmlString.Append(dt.Columns[j].ColumnName.ToString() + "=\"" + dt.Rows[i][j].ToString() + "\" ");

                        //if (j < dt.Columns.Count - 1)
                        //{
                        //    XmlString.Append( dt.Columns[j].ColumnName.ToString() + "=\"" + dt.Rows[i][j].ToString() + "\" ");
                        //}
                        //else if (j == dt.Columns.Count - 1)
                        //{
                        //    XmlString.Append(dt.Columns[j].ColumnName.ToString() + "=\"" + dt.Rows[i][j].ToString() + "\" >");
                        //}
                    }

                    if ("" == newsContent)
                    {
                        XmlString.Append("/>");
                    }
                    else
                    {
                        XmlString.Append("><![CDATA[");
                        XmlString.Append(newsContent);
                        XmlString.Append("]]></item>");
                    }



                    //if (i == dt.Rows.Count - 1)
                    //{
                    //    JsonString.Append("} ");
                    //}
                    //else
                    //{
                    //    JsonString.Append("}, ");
                    //}
                }
                XmlString.Append("</TinyNews>");
                return XmlString.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 反回JSON数据到前台
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <returns>JSON字符串</returns>
        public static string dataTableToJson(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                //JsonString.Append("{ ");
                JsonString.Append("[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 设置null object为 空字符串
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static string resetNull2Empty(object target)
        {
            return null == target ? "" : target.ToString();
        }


        /// <summary>
        /// 格式化数据成JSON字符串
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string format2Json(object key, object value)
        {
            return string.Format("\"{0}\":{1}",
                new object[]
                {
                    key, 
                    value
                });
        }
    }
}
